<template>
  <div v-bkloading="{ isLoading }" class="file-manage-source-file">
    <list-action-layout>
      <template>
        <jb-form ref="form" class="job-search" fixed :label-width="80">
          <jb-form-item label="条件检索" :style="{ marginBottom: 0 }">
            <bk-radio-group :value="conditionalSearchStatus" @change="handleScriptSourceChange">
              <bk-radio-button :value="-1">
                全部
              </bk-radio-button>
              <bk-radio-button :value="1">
                用户名/状态
              </bk-radio-button>
              <bk-radio-button :value="2">
                ID
              </bk-radio-button>
              <bk-radio-button :value="3">
                作业名称索
              </bk-radio-button>
            </bk-radio-group>
          </jb-form-item>
          <jb-form-item :style="{ margin: 0 }">
            <template v-if="conditionalSearchStatus == -1">
              <jb-search-select :key="conditionalSearchStatus" ref="search" :data="searchSelectAll" :parse-url="true"
                placeholder="排序" style="width: 480px;" @on-change="handleSearch" />
            </template>
            <template v-if="conditionalSearchStatus == 1">
              <jb-search-select :key="conditionalSearchStatus" ref="search" :data="searchSelect" :parse-url="true"
                placeholder="搜索用户、状态、排序" style="width: 480px;" @on-change="handleSearch" />
            </template>
            <template v-if="conditionalSearchStatus == 2">
              <jb-search-select :key="conditionalSearchStatus" ref="search" :data="searchSelectById" :parse-url="true"
                placeholder="通过ID模糊搜索、排序" style="width: 480px;" @on-change="handleSearch" />
            </template>
            <template v-if="conditionalSearchStatus == 3">
              <jb-search-select :key="conditionalSearchStatus" ref="search" :data="searchSelectByJobName"
                :parse-url="true" placeholder="通过作业名称模糊搜索、排序" style="width: 480px;" @on-change="handleSearch" />
            </template>
          </jb-form-item>
        </jb-form>
      </template>
    </list-action-layout>
    <render-list ref="jobSourcelist" :data-source="fetchJobSourceList" :search-control="() => $refs.search"
      :size="tableSize">
      <bk-table-column key="id_job" align="left" label="ID" prop="id_job" sortable width="80px" />
      <bk-table-column key="job_name" align="left" label="作业名称" prop="job_name" show-overflow-tooltip sortable />

      <bk-table-column key="nodelist" align="center" label="节点名称" prop="nodelist" />
      <bk-table-column key="partition" align="center" label="队列分区" prop="partition" width="80px" />
      <bk-table-column key="work_dir" align="center" label="工作目录" prop="work_dir" show-overflow-tooltip />
      <bk-table-column key="state" label="状态" prop="state" width="120px">
        <template slot-scope="{ row }">
          <span :style="{
            verticalAlign: 'middle',
            borderRadius: '5px',
            width: '10px',
            height: '10px',
            background: getColor(row.state).color,
            display: 'inline-block',
          }" />
          <span style="vertical-align: middle;">{{ getColor(row.state).name }}</span>
        </template>
      </bk-table-column>
      <bk-table-column key="time_durntion" label="时长" prop="time_durntion" width="120px">
        <div slot-scope="{ row }">
          {{ formatTime(row.time_end, row.time_start) }}
        </div>
      </bk-table-column>
      <bk-table-column key="time_end" label="结束时间" prop="time_end" width="180px">
        <div slot-scope="{ row }">
          {{ changeTime(row.time_end) }}
        </div>
      </bk-table-column>
      <bk-table-column key="action" label="操作" width="140">
        <div slot-scope="{ row }" class="action-box">
          <jb-popover-confirm :confirm-handler="() => handleDelete(row)" content="该操作只删除当前作业记录,不影响其他的内容"
            title="确定终止此任务？">
            <bk-button :disabled="!(([ '1', '2' ].indexOf(`${row.state}`) != -1))" :resource-id="row.id" text
              theme="danger">
              终止
            </bk-button>
          </jb-popover-confirm>

          <jb-popover-confirm :confirm-handler="() => hanlderView(row, 'view')" confirm-text="查看详情"
            :content="`${getOutputPath(row) || row.std_out.replace('%j', row.id_job) || '--'}`"
            :title="`任务：${row.job_name} 的日志路径`">
            <bk-button :resource-id="row.id" :style="{ margin: '0 5px' }" text>
              日志详情
            </bk-button>
          </jb-popover-confirm>

          <!-- <bk-button text @click="() => hanlderView(row, 'folder')">打开目录</bk-button> -->
        </div>
      </bk-table-column>
    </render-list>
    <jb-dialog v-model="isShowFileRelate" header-position="left" ok-text="确定" title="文件管理"
      :width="drectoryScrollParams.model == 'view' ? 880 : 780">
      <div class="drectory-scroll-inner">
        <drectory-scroll v-if="isShowFileRelate" :params="drectoryScrollParams" />
      </div>
    </jb-dialog>
  </div>
</template>
<script>
import AccountManageService from '@service/account-manage';
import SlurmService from '@service/slurm';
import UserService from '@service/user';

import { getDefaultName } from '@utils/assist/generator-default-value';
import { prettyDateTimeFormat } from '@utils/assist/time';
import {
  listColumnsCache,
} from '@utils/cache-helper';

import JbPopoverConfirm from '@components/jb-popover-confirm';
import JbSearchSelect from '@components/jb-search-select';
import ListActionLayout from '@components/list-action-layout';
import RenderList from '@components/render-list';

import DrectoryScroll from '@/components/drectory-scroll';
import I18n from '@/i18n';


const TABLE_COLUMN_CACHE = 'file_source_list_columns';

const jobStatus = () => ([{
  name: '全部',
  color: '#5bc0de',  // 黄色
  id: '-1',
}, {
  name: '等待中',
  color: '#f0ad4e',  // 黄色
  id: '0',
}, {
  name: '运行中(1)',
  color: '#5bc0de',  // 蓝色
  id: '1',
}, {
  name: '运行中(2)',
  color: '#5bc0de',  // 蓝色
  id: '2',
}, {
  name: '已完成',
  color: '#28a745',  // 绿色
  id: '3',
}, {
  name: '已取消',
  color: '#d9534f',  // 红色
  id: '4',
}, {
  name: '失败',
  color: '#d9534f',  // 红色
  id: '5',
}, {
  name: '超时',
  color: '#f0ad4e',  // 黄色
  id: '6',
},
]);

const defultParams = () => ([{
  id: 'orderBy',
  name: '排序',
  children: [{
    name: '倒序',
    id: 'DESC',
  }, {
    name: '正序',
    id: 'ASC',
  }],
}]);
export default {
  name: 'SourceFile',
  components: {
    RenderList,
    ListActionLayout,
    JbSearchSelect,
    JbPopoverConfirm,
    DrectoryScroll,
  },
  data() {
    return {
      isShowFileRelate: false, // 文件系统可视化
      isLoading: false,
      tableSize: 'small',
      searchParams: {
        page: 1,
        pageSize: 10,
        total: 0,
        account: 'root',
        state: '-1',
        orderBy: 'DESC',
      },
      selectedTableColumn: [],
      fileSourceDetailInfo: {},
      isShowSideslider: false,
      conditionalSearchStatus: -1,
      userInfor: {},
      drectoryScrollParams: {
        model: 'view',
        path: '',
      },
    };
  },
  computed: {
    isSkeletonLoading() {
      return this.$refs.jobSourcelist.isLoading;
    },
    allRenderColumnMap() {
      return this.selectedTableColumn.reduce((result, item) => {
        result[item.id] = true;
        return result;
      }, {});
    },
  },
  created() {
    this.getCurUserInfor();
    this.fetchJobSourceList = this.fetchData;
    this.getAccountList();

    this.searchSelect = [
      {
        id: 'account',
        name: I18n.t('用户'),
        default: true,
      }, {
        id: 'state',
        name: '作业状态',
        children: [...jobStatus()],
      },
      ...defultParams(),
    ];

    this.searchSelectAll = [
      ...defultParams(),
    ];

    this.searchSelectById = [
      {
        id: 'id',
        name: 'ID',
        default: true,
      },
      ...defultParams(),
    ];
    this.searchSelectByJobName = [
      {
        id: 'job_name',
        name: '作业名称',
        default: true,
      },
      ...defultParams(),
    ];
  },
  mounted() { },
  methods: {
    getOutputPath(row, model = 'view') {
      const match = row.submit_line.match(/output=(.*?)--wrap/);  // 查找匹配项
      return model == 'view' ? match[1] : match[1].split('logs/')[0];
    },
    hanlderView(row, model) {
      this.drectoryScrollParams = {
        model,
        path: this.getOutputPath(row, model) || `${row.std_out.replace('%j', row.id_job) || '--'}`,
      };
      if (model == 'folder') {
        this.drectoryScrollParams.path = this.drectoryScrollParams.path.split('logs')[0];
      }
      this.isShowFileRelate = true;
    },
    async getCurUserInfor() {
      const data = await UserService.fetchUserInfo();
      this.userInfor = data;
    },
    handleScriptSourceChange(source) {
      this.conditionalSearchStatus = source;
    },
    geData() {
      this.$refs.jobSourcelist.$emit('onFetch', {
        ...this.searchParams,
      });
    },
    fetchData(param = {}) {
      const { modelByUser: userName, scopeName: orgName } = getDefaultName();
      const params = { ...param, userName, orgName };
      if (this.conditionalSearchStatus == -1) {
        return SlurmService.getJobAllList(params).then(({ data }) => ({ data: data.items, total: data.total }));
      }
      if (this.conditionalSearchStatus == 1) {
        if (params.state && params.state != '' && params.state != -1) {
          return SlurmService.getAccountJobListBystate(params).then(({ data }) => ({ data: data.items, total: data.total }));
        }
        return SlurmService.getAccountJobList(params).then(({ data }) => ({ data: data.items, total: data.total }));
      }
      if (this.conditionalSearchStatus == 2) {
        return SlurmService.getJobById(params).then(({ data }) => ({ data: data.items, total: data.total }));
      }
      if (this.conditionalSearchStatus == 3) {
        return SlurmService.getJobByJobName(params).then(({ data }) => ({ data: data.items, total: data.total }));
      }
    },
    changeTime(time) {
      return prettyDateTimeFormat(time * 1000);
    },
    getColor(val) {
      return jobStatus().filter(item => item.id == `${val}`)[0] || {};
    },

    /**
     * @desc 设置表格显示列/表格size
     */
    handleSettingChange({ fields, size }) {
      this.selectedTableColumn = Object.freeze(fields);
      this.tableSize = size;
      listColumnsCache.setItem(TABLE_COLUMN_CACHE, {
        columns: fields,
        size,
      });
    },

    /**
     * @desc 过滤表格数据
     * @param {Array} payload 用户输入的过滤数据
     *
     * 重新拉取数据
     */
    handleSearch(payload) {
      this.searchParams = { ...this.searchParams, ...payload };
      this.geData();
    },

    /**
     * @desc 删除文件源
     * @param {Number} id 文件源id
     *
     * 删除成功重新拉取数据
     */
    handleDelete(id) {
      SlurmService.handlerCancelJob({
        job_id: `${id.id_job}`,
      }).then(() => {
        this.messageSuccess(I18n.t('file.删除成功'));
        this.geData();
      });
    },

    formatTime(end, start) {
      if (!end || !start) return '--';
      const seconds = (end - start) * 1;
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;

      // 格式化为两位数
      const formattedTime = [
        hours.toString().padStart(2, '0'),
        minutes.toString().padStart(2, '0'),
        secs.toString().padStart(2, '0'),
      ].join(':');

      return formattedTime;
    },
    getAccountList() {
      AccountManageService.fetchAccountWhole().then((data) => {
        this.searchSelect[0].children = data.map(({ account }) => ({ id: account, name: account }));
      });
    },
  },
};
</script>
<style lang="postcss">
.drectory-scroll-inner {
  min-height: 450px;
}

.file-manage-source-file {
  .action-box {
    display: flex;
    align-items: center;
  }
}

.job-search {
  .bk-form {
    display: flex;
  }

  .bk-form-control {
    display: flex;
  }

  .search-nextfix {
    top: 0 !important;
  }

}
</style>
